﻿using BaGet.Protocol;
using BaGet.Protocol.Models;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Win32;
using NuGet.Versioning;
using System.IO;
using System.Windows.Input;

namespace Niaofei.Nuget
{
    public class DownloadWindowViewModel : ObservableObject
    {
        private string _path = "";

        private readonly NiaofeiNuGetClient _client;
        private readonly SearchResult _nuget;

        public DownloadWindowViewModel(SearchResult nuget)
        {
            _nuget = nuget;

            DownLoadCommand = new AsyncRelayCommand(Download);
            SelectPathCommand = new RelayCommand(SelectPath);
            _client = new NiaofeiNuGetClient("https://api.nuget.org/v3/index.json");
        }

        public ICommand DownLoadCommand { get; set; }
        public ICommand SelectPathCommand { get; set; }


        public string Path
        {
            get => _path;
            set
            {
                _path = value;
                OnPropertyChanged();
            }
        }

        private void SelectPath()
        {
            var folderBrowserDialog = new OpenFolderDialog();

            if (folderBrowserDialog.ShowDialog() == true)
            {
                Path = folderBrowserDialog.FolderName;
            }
        }

        private async Task Download()
        {
            await Download(_nuget.PackageId, _nuget.Version);
        }

        private async Task Download(string packageId, string version)
        {
            var result = await _client.MetadataClient.GetRegistrationIndexOrNullAsync(packageId);

            var metadata = result.Pages.Where(m => m.ItemsOrNull != null)
                .SelectMany(m => m.ItemsOrNull)
                .Where(m => m.PackageMetadata.Version == version)
                .FirstOrDefault()?.PackageMetadata;

            var nugetStream = await _client.ContentClient.DownloadPackageOrNullAsync(packageId, NuGetVersion.Parse(version));
            var nugetPath = System.IO.Path.Combine(Path, $"{packageId}.{version}.nupkg");

            using var fileStream = new FileStream(nugetPath, FileMode.OpenOrCreate, FileAccess.Write);
            nugetStream.CopyTo(fileStream);

            if (metadata?.DependencyGroups.FirstOrDefault()?.Dependencies != null)
            {
                foreach (var dependency in metadata?.DependencyGroups.FirstOrDefault()?.Dependencies!)
                {
                    await Download(dependency.Id, dependency.ParseRange().MinVersion.ToString());
                }
            }
        }
    }
}
